import { NavBar, SearchBar } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router'
import { useEffect, useState } from 'react'
import { Dispatch } from 'redux'
import { RootState } from '@/types/store'
import { getSuggestion, clearSuggestion } from '@/store/actions/search'

import { useDebounceFn } from 'ahooks'
import classNames from 'classnames'

import { Icon } from '@/components/Icon'
import styles from './index.module.scss'

const GEEK_SEARCH_KEY = 'geek-history'

const Search = () => {
  const history = useHistory()
  const dispatch = useDispatch<Dispatch<any>>()
  const [searchText, setSearchText] = useState('')
  const { suggestion } = useSelector((state: RootState) => state.search)
  const [searchHistory, setSearchHistory] = useState<string[]>([])

  useEffect(() => {
    const localHistory = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]'
    ) as string[]

    setSearchHistory(localHistory)
  }, [])

  const { run: debounceFn } = useDebounceFn(
    (value) => {
      dispatch(getSuggestion(value))
    },
    {
      wait: 500,
    }
  )

  const onSearchChange = (value: string) => {
    setSearchText(value)
    if (value.trim() === '') {
      dispatch(clearSuggestion())
      return
    }

    debounceFn(value)
  }

  const highLightSuggestion = suggestion.map((item) => {
    const lowerSearchText = searchText.toLowerCase()
    const lowerSuggestionItem = item.toLowerCase()

    const searchIndex = lowerSuggestionItem.indexOf(lowerSearchText)

    const left = item.slice(0, searchIndex)
    const search = item.slice(searchIndex, searchIndex + lowerSearchText.length)
    const right = item.slice(searchIndex + lowerSearchText.length)

    return {
      left,
      search,
      right,
      raw: item,
    }
  })

  const onSearch = (searchValue: string) => {
    console.log(searchValue)
    history.push(`/search/result?query=${searchValue}`)
    dispatch(clearSuggestion())
    saveHistories(searchValue)
  }

  const saveHistories = (value: string) => {
    let localHistory = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]'
    ) as string[]
    if (localHistory.length === 0) {
      localHistory.push(value)
    } else {
      if (localHistory.indexOf(value) > -1) {
        localHistory = [value, ...localHistory.filter((item) => item !== value)]
      } else {
        localHistory.push(value)
      }
    }
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(localHistory))
  }

  const delHistory = (value: string) => {
    const localHistory = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]'
    ) as string[]
    const newLocalHistory = localHistory.filter((item) => item !== value)
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(newLocalHistory))
    setSearchHistory(newLocalHistory)
  }
  const clearAllHistory = () => {
    localStorage.removeItem(GEEK_SEARCH_KEY)
    setSearchHistory([])
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => onSearch(searchText)}>
            搜索
          </span>
        }
      >
        <SearchBar
          value={searchText}
          placeholder="请输入关键字搜索"
          onChange={onSearchChange}
        />
      </NavBar>

      {suggestion.length <= 0 && (
        <div
          className="history"
          style={{
            display: searchHistory.length > 0 ? 'block' : 'none',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clearAllHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {searchHistory.map((item, index) => (
              <span
                key={index}
                className="history-item"
                onClick={() => delHistory(item)}
              >
                <span className="text-overflow">{item}</span>
                <Icon type="iconbtn_essay_close" />
              </span>
            ))}
          </div>
        </div>
      )}

      <div
        className={classNames('search-result', {
          show: suggestion.length > 0,
        })}
      >
        {highLightSuggestion.map((item, index) => (
          <div
            key={index}
            className="result-item"
            onClick={() => onSearch(item.raw)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div className="result-value text-overflow">
              {/* <span>黑马</span>
              程序员 */}
              {/* {item} */}
              {item.left}
              <span>{item.search}</span>
              {item.right}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Search
